# recommendations.py
import pandas as pd
from django.db.models import Max
from content.models import Goods




def calculate_daily_recommendations():
    # 获取所有有效商品数据（过滤空价格和空评分）
    goods_qs = Goods.objects.exclude(price__isnull=True).exclude(rating__isnull=True)

    # 转换为DataFrame并强制类型转换
    goods_data = goods_qs.values('id', 'rating', 'price', 'category')
    df = pd.DataFrame.from_records(goods_data)

    if df.empty:
        return

    # 关键修正1：将Decimal字段转换为float
    df['rating'] = pd.to_numeric(df['rating'], errors='coerce').astype(float)
    df['price'] = pd.to_numeric(df['price'], errors='coerce').astype(float)

    # 过滤转换失败的行
    df = df.dropna(subset=['rating', 'price'])

    # 关键修正2：归一化使用float运算
    max_price = df['price'].max()
    df['normalized_rating'] = df['rating'] / 5.0  # 满分为5分，直接使用float
    df['normalized_price'] = 1 - (df['price'] / max_price)

    # 关键修正3：权重使用float
    weights = {
        'rating': 0.6,  # 改为float类型
        'price': 0.4
    }

    # 计算综合得分（全部float运算）
    df['score'] = (
            weights['rating'] * df['normalized_rating'] +
            weights['price'] * df['normalized_price']
    )

    # 按类别分组取TOP2
    recommended_ids = []
    for category in df['category'].unique():
        category_df = df[df['category'] == category]
        if not category_df.empty:
            # 关键修正4：确保score列是float
            top_2 = category_df.nlargest(2, 'score')
            recommended_ids.extend(top_2['id'].tolist())

    # 全局保底推荐
    if not recommended_ids:
        recommended_ids = df.nlargest(10, 'score')['id'].tolist()
    else:
        # 去重并限制总数
        recommended_ids = list(set(recommended_ids))[:10]

        # 更新数据库
    # print('==========1',recommended_ids)
    Goods.objects.update(is_recommended=False)
    Goods.objects.filter(id__in=recommended_ids).update(is_recommended=True)


